#include "driver/spi_master.h"
#include "esp_system.h"
#include <string.h>

#define WS2812B_DATA_PIN 7

static spi_device_handle_t spi;

int esp32c3_spi_init(void)
{
	esp_err_t ret;
	spi_bus_config_t buscfg = {
		.miso_io_num = 2,
		.mosi_io_num = WS2812B_DATA_PIN,
		.sclk_io_num = 6,
		.quadwp_io_num = -1,
		.quadhd_io_num = -1,
		.max_transfer_sz = 16,
	};

	spi_device_interface_config_t devcfg = {
		.clock_speed_hz = 2400000, // Clock out at 2.4 MHz
		.mode = 0,                 // SPI mode 0
		.spics_io_num = 10,        // CS pin
		.queue_size = 7,           // We want to be able to queue 7 transactions at a time
	};

	ret = spi_bus_initialize(SPI2_HOST, &buscfg, SPI_DMA_CH_AUTO);
	ESP_ERROR_CHECK(ret);

	ret = spi_bus_add_device(SPI2_HOST, &devcfg, &spi);
	ESP_ERROR_CHECK(ret);

	return 0;
}

void esp32c3_spi_write(uint8_t* bytes, uint32_t len)
{
	uint32_t section = 4096;
	spi_transaction_t t;

	if (!len) {
		return;
	}

	while (len > section) {
		memset(&t, 0, sizeof(t));             // Zero out the transaction
		t.length = 8 * section;               // Command is 8 bits
		t.tx_buffer = bytes;                  // The data is the cmd itself
		spi_device_polling_transmit(spi, &t); // Transmit!
		bytes += section;
		len -= section;
	}

	memset(&t, 0, sizeof(t));             // Zero out the transaction
	t.length = 8 * len;                   // Command is 8 bits
	t.tx_buffer = bytes;                  // The data is the cmd itself
	spi_device_polling_transmit(spi, &t); // Transmit!
}
